Page({
  data: {
    phone: '',
    code: '',
    phoneError: '',
    codeError: '',
    isCounting: false,
    countDown: 60,
    countDownText: '获取验证码',
    showSkip: true
  },

  onPhoneInput(e) {
    const phone = e.detail.value;
    this.setData({ phone });
    this.validatePhone();
  },

  validatePhone() {
    const phone = this.data.phone;
    let phoneError = '';
    if (!phone) {
      phoneError = '请输入手机号';
    } else if (!/^1[3-9]\d{9}$/.test(phone)) {
      phoneError = '手机号格式不正确';
    }
    this.setData({ phoneError });
  },

  getCode() {
    if (this.data.isCounting || this.data.phoneError) return;
    const phone = this.data.phone;
    wx.request({
      url: 'https://api.example.com/sendCode',
      method: 'POST',
      data: { phone },
      success: (res) => {
        if (res.data.code === 0) {
          this.startCountDown();
        } else {
          wx.showToast({ title: res.data.msg, icon: 'none' });
        }
      }
    });
  },

  startCountDown() {
    this.setData({ isCounting: true, countDownText: `60s后重发` });
    const timer = setInterval(() => {
      if (this.data.countDown <= 1) {
        clearInterval(timer);
        this.setData({ isCounting: false, countDown: 60, countDownText: '获取验证码' });
      } else {
        this.setData({ countDown: this.data.countDown - 1, countDownText: `${this.data.countDown - 1}s后重发` });
      }
    }, 1000);
  },

  onCodeInput(e) {
    this.setData({ code: e.detail.value });
  },

  onConfirm() {
    const { phone, code } = this.data;
    wx.request({
      url: 'https://api.example.com/bindPhone',
      method: 'POST',
      data: { phone, code },
      success: (res) => {
        if (res.data.code === 0) {
          wx.showToast({ title: '绑定成功', icon: 'success' });
          wx.navigateBack({ delta: 1 });
        } else {
          wx.showToast({ title: res.data.msg, icon: 'none' });
        }
      }
    });
  },

  onSkip() {
    wx.navigateBack({ delta: 1 });
  }
})